package resource

import (
	"mallgo/internal/common/response"
	"mallgo/internal/resources/app/api/domain/request"
	"mallgo/internal/resources/app/model"
	"time"

	"gorm.io/gorm"
)

type AppResource struct {
	db *gorm.DB
}

func NewAppResource(db *gorm.DB) *AppResource {
	return &AppResource{db}
}

// Create 创建应用
func (h *AppResource) Create(req *request.AppRequest) *response.ResponseObject {
	// 检查AppKey是否已存在
	var existingApp model.App
	if err := h.db.Where("app_key = ?", req.AppKey).First(&existingApp).Error; err == nil {
		return response.Error(500, "该应用key已存在")
	}

	// 创建应用
	app := model.App{
		AppKey:   req.AppKey,
		Name:     req.Name,
		Note:     req.Note,
		AddDate:  time.Now(),
		LastDate: time.Now(),
	}

	if err := h.db.Create(&app).Error; err != nil {
		return response.Error(500, "创建应用失败")
	}

	return response.Success(app)
}

// Update 更新应用
func (h *AppResource) Update(id int64, req *request.AppRequest) *response.ResponseObject {
	var app model.App
	if err := h.db.First(&app, id).Error; err != nil {
		return response.Error(500, "应用不存在")
	}

	// 检查AppKey是否与其他记录重复
	if req.AppKey != app.AppKey {
		var existingApp model.App
		if err := h.db.Where("app_key = ? AND id != ?", req.AppKey, id).First(&existingApp).Error; err == nil {
			return response.Error(500, "该应用key已存在")
		}
	}

	// 更新应用信息
	updates := map[string]interface{}{
		"app_key":   req.AppKey,
		"name":      req.Name,
		"note":      req.Note,
		"last_date": time.Now(),
	}

	if err := h.db.Model(&app).Updates(updates).Error; err != nil {
		return response.Error(500, "更新应用失败")
	}

	return response.Success(app)
}

// Delete 删除应用
func (h *AppResource) Delete(id int64) *response.ResponseObject {
	if err := h.db.Delete(&model.App{}, id).Error; err != nil {
		return response.Error(500, "删除应用失败")
	}

	return response.Success(nil)
}

// Get 获取应用详情
func (h *AppResource) Get(id int64) *response.ResponseObject {
	var app model.App
	if err := h.db.First(&app, id).Error; err != nil {
		return response.Error(500, "应用不存在")
	}

	return response.Success(app)
}

// Query 查询应用列表
func (h *AppResource) Query(req *request.AppRequest) *response.PageResponse {
	var apps []model.App
	var total int64
	query := h.db.Model(&model.App{})

	// 添加查询条件
	if req.AppKey != "" {
		query = query.Where("app_key LIKE ?", "%"+req.AppKey+"%")
	}
	if req.Name != "" {
		query = query.Where("name LIKE ?", "%"+req.Name+"%")
	}

	// 获取总数
	if err := query.Count(&total).Error; err != nil {
		return response.ErrorPage(500, "查询应用总数失败")
	}

	// 分页查询
	page := req.Page
	if page <= 0 {
		page = 1
	}
	pageSize := req.Size
	if pageSize <= 0 {
		pageSize = 10
	}
	offset := (page - 1) * pageSize

	// 执行分页查询
	if err := query.Offset(offset).Limit(pageSize).Order("id DESC").Find(&apps).Error; err != nil {
		return response.ErrorPage(500, "查询应用失败")
	}

	return response.SuccessPage(apps, page, pageSize, total)
}
